from django.shortcuts import render, HttpResponseRedirect
from django.http.response import JsonResponse
from django import forms
from host import models
from django.core.exceptions import ValidationError
import random


# 添加主机校验
class Form(forms.Form):
    hostalias = forms.CharField(max_length=128)
    port = forms.IntegerField()
    username = forms.CharField(max_length=128)
    ip = forms.CharField(max_length=16)
    pwd = forms.Textarea()
    mode = forms.IntegerField()

    def clean_mode(self):
        val = self.cleaned_data.get("mode")
        _ = [0, 1]
        if _.count(val):
            return val
        raise ValidationError("0,1")


# Create your views here.
def index(request):
    return render(request, "index.html")


def list(request):
    if request.method == 'POST':
        host = Form(request.POST)
        if host.is_valid():
            models.Host.objects.create(**host.cleaned_data)
        else:
            print(host.errors)
        return HttpResponseRedirect("list")

    hosts = models.Host.objects.all()
    return render(request, "host/index.html", {'hosts': hosts})


# 远程链接
def like(request):
    if request.method == 'GET':
        data = {"host": request.GET.get("id"), "openid": random.randint(0, 100000), "operator": request.user.username}
        return render(request, "host/link.html", {"data": data})


def video(request):
    videos = models.HostVideo.objects.all()
    return render(request, 'host/video.html', {"videos": videos})


def videos(request):
    id = request.GET.get('id')
    video = models.HostVideo.objects.filter(pk=id)
    if video.first():
        return render(request, 'host/videos.html', {'video': video[0]})
    return render(request, 'host/videos.html')
